<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item name="createBy">
              <template #label><span title="创建人">创建人</span></template>
              <a-input placeholder="请输入创建人" v-model:value="queryParam.createBy"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="carNumber">
              <template #label><span title="车牌号">车牌号</span></template>
              <a-input placeholder="请输入车牌号" v-model:value="queryParam.carNumber"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="6">
              <a-form-item name="status">
                <template #label><span title="预约状态">预约状态</span></template>
                <j-dict-select-tag placeholder="请选择预约状态" v-model:value="queryParam.status" dictCode="subscribe_status" />
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="carStatus">
                <template #label><span title="车辆状态">车辆状态</span></template>
                <j-dict-select-tag placeholder="请选择车辆状态" v-model:value="queryParam.carStatus" dictCode="get_out_status" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <a @click="handlePastDue(record)">过期</a>
        <Divider type="vertical" class="action-divider" />
        <a @click="handleParkingLot(record)">进场</a>
        <Divider type="vertical" class="action-divider" />
        <a @click="handleDetail(record)">详情</a>
        <Divider type="vertical" class="action-divider" />
        <a @click="handleEdit(record)">编辑</a>
        <Divider type="vertical" class="action-divider" />
        <a-popconfirm title="是否确认删除?" ok-text="确定" cancel-text="取消" @confirm="handleDelete" @cancel="cancel">
          <a>删除</a>
        </a-popconfirm>
      </template>
      <template v-slot:bodyCell="{ column, record, index, text }"> </template>
    </BasicTable>
    <!-- 表单区域 -->
    <ParkingReservationManagementModal ref="registerModal" @success="handleSuccess"></ParkingReservationManagementModal>
  </div>
</template>

<script lang="ts" name="parkingReservationManagement-parkingReservationManagement" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns } from './ParkingReservationManagement.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, editUpdate } from './ParkingReservationManagement.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import ParkingReservationManagementModal from './components/ParkingReservationManagementModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import { savePaymentManagementData } from '../paymentManagement/PaymentManagement.api';
  import { message, Divider } from 'ant-design-vue';
  import { getMallParkingSpaceList, saveOrUpdateForMallParking } from '../mallParkingSpace/MallParkingSpace.api';
  import { sendMessageTest } from '../system/message/template/template.api';

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '车位预约管理',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 230,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '车位预约管理',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] =
    tableContext;
  const labelCol = reactive({
    xs: 24,
    sm: 4,
    xl: 6,
    xxl: 4,
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
  function cancel() {}

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  /**
   * 设置过期事件
   * @param record
   */
  function handlePastDue(record: Recordable) {
    if (record.status == '3') {
      message.warning('该车位已经过期');
      return;
    }
    editUpdate({ ...record, status: '3' }).then((res) => {
      if (res.success) {
        saveOrUpdateForMallParking({ ...record, status: '2' }, true);
        reload();
        const params = {
          msgType: 'system',
          receiver: record.createBy,
          templateCode: '车位预约过期',
          templateContent: '请注意：当前预约车位已过期，请重新预约！',
          templateName: '车位预约过期',
        };
        sendMessageTest(params);
        message.success('操作成功');
      } else {
        message.error(res.message);
      }
    });
  }

  /**
   * 车辆进场
   */
  function handleParkingLot(record: Recordable) {
    console.log('handleParkingLot ==>', record);
    if (record.status == '3') {
      message.warning('该车位已经过期，请重新预约');
      return;
    }
    if (record.carStatus != '4') {
      message.warning('当前车位已进场，请勿重复进场');
      return;
    }
    const params = {
      address: `${record.location}`,
      createBy: record.createBy,
      carNumber: record.carNumber,
      berthNumber: record.carportNumber,
      startTime: formatToDateTime(new Date()),
      endTime: '',
      getOutStatus: '1',
      payStatus: '1',
      durationParking: '',
      price: 5,
      payAmount: 0,
      actualAmount: 0,
      oldAmount: 0,
      id: '',
    };
    editUpdate({ ...record, carStatus: '3' }).then((res) => {
      if (res.success) {
        savePaymentManagementData(params);
        loadCarPortData(record.carportNumber);
        reload();
        const params1 = {
          msgType: 'system',
          receiver: record.createBy,
          templateCode: '车辆进场提示',
          templateContent: '当前车辆已经进场，开始计费。',
          templateName: '车辆进场提示',
        };
        sendMessageTest(params1);
        message.success('操作成功');
      } else {
        message.error(res.message);
      }
    });
  }

  function loadCarPortData(number) {
    const params = {
      column: 'createTime',
      order: 'desc',
      pageNo: 1,
      pageSize: 10,
      number: number,
    };
    getMallParkingSpaceList(params).then((res) => {
      if (res.records.length > 0) {
        const data = res.records;
        saveOrUpdateForMallParking({ ...data[0], status: '2' }, true);
      }
    });
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust {
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }

    .flex-between {
      width: 100%;
      background: crimson;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
</style>
